import React, { createContext, ReactElement } from 'react';

import { State, Action, Context } from './types';
import actions from './actions';
import Provider from '../../components/Provider';
import { LOGIN_TYPE } from './constant';

export const initialState: State = {
  verifyText: '获取验证码',
  verifyDisabled: false,
  phoneNumber: '',
  verifyCode: '',
  hasShownAlert: false,
  password: '',
  isShowPassword: false,
  loginType: LOGIN_TYPE.Verify,
  isBind: false,
  showAgreement: false
};

export const reducer = (state: State, action: Action): State => {
  switch (action.type) {
    case 'SEND_VERIFY_CODE':
      return { ...state, verifyDisabled: true, verifyText: '已发送' };
    case 'SEND_VERIFY_CODE_FINISH':
      return { ...state, verifyDisabled: false, verifyText: '重发' };
    case 'COUNTDOWN_VERIFY_CODE':
      return { ...state, verifyText: `已发送(${action.value}s)` };
    case 'SET_PHONE_NUMBER':
      return { ...state, phoneNumber: action.value };
    case 'SET_VERIFY_CODE':
      return { ...state, verifyCode: action.value };
    case 'SET_HAS_SHOWN_ALERT':
      return { ...state, hasShownAlert: action.value };
    case 'SET_PASSWORD':
      return { ...state, password: action.value };
    case 'SET_IS_SHOW_PASSWORD':
      return { ...state, isShowPassword: action.value };
    case 'SET_LOGIN_TYPE':
      return { ...state, loginType: action.value };
    case 'SET_SHOW_AGREEMENT':
      return { ...state, showAgreement: action.value };
    case 'SET_IS_BIND':
      return { ...state, isBind: action.value };
    default:
      return state;
  }
};

export const Store = createContext<Context>({
  state: initialState
});

export default (props: { [key: string]: any }): ReactElement => {
  return (
    <Provider
      reducer={reducer}
      initialState={initialState}
      Store={Store}
      actions={actions}
      {...props}
    />
  );
};
